package com.zjj.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.zjj.reggie.common.BaseContext;
import com.zjj.reggie.common.CustomExcepion;
import com.zjj.reggie.entity.*;
import com.zjj.reggie.mapper.OrdersMapper;
import com.zjj.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService usersService;

    @Autowired
    private AddressBookService addressService;

    @Autowired
    private OrderDetailService orderDetailService;
    /**
     * 提交订单
     * @param order
     */


    @Transactional
    public void submit(Orders order) {
        //当前用户id
        Long userid = BaseContext.getCurrentId();
        log.info("当前用户id："+userid);

        //查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userid);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(queryWrapper);

        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            throw new CustomExcepion("购物车为空，无法提交订单");
        }

        //查询用户数据
        User user = usersService.getById(userid);
        log.info("当前用户数据："+user.getName());
        //查询地址数据
        Long addressBookId = order.getAddressBookId();
        AddressBook addressBook = addressService.getById(addressBookId);
        if (addressBook == null) {
            throw new CustomExcepion("地址不存在，无法提交订单");
        }
        long orderId = IdWorker.getId();//生成订单id

        //AtomicInteger保证线程安全原子操作
        AtomicInteger amount = new AtomicInteger(0);//订单总金额

        //转换订单明细数据
        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);//设置订单id
            orderDetail.setNumber(item.getNumber());//设置数量
            orderDetail.setDishFlavor(item.getDishFlavor());//设置口味
            orderDetail.setDishId(item.getDishId());//设置菜品id
            orderDetail.setName(item.getName());//设置菜品名称
            orderDetail.setImage(item.getImage());//设置菜品图片
            orderDetail.setAmount(item.getAmount());//设置单价
            orderDetail.setSetmealId(item.getSetmealId());//设置套餐id
            //计算总金额addAndGet累加  multiply乘以数量
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;

        }).collect(Collectors.toList());


        //向订单表插入数据，一条数据
        order.setUserId(orderId);//设置订单id
        order.setOrderTime(LocalDateTime.now());//设置下单时间
        order.setCheckoutTime(LocalDateTime.now());//设置支付时间
        order.setStatus(2);//设置订单状态为待发货
        order.setAmount(new BigDecimal(amount.get()));//设置订单金额
        order.setUserId(userid);//设置用户id
        order.setNumber(String.valueOf(orderId));//设置订单号
        order.setUserName(user.getName());//设置用户名
        order.setConsignee(addressBook.getConsignee());//设置收货人
        order.setPhone(addressBook.getPhone());//设置手机号
        order.setAddress((addressBook.getProvinceName()==null?"":addressBook.getProvinceName())
                + (addressBook.getCityName()==null?"":addressBook.getCityName())
                + (addressBook.getDistrictName()==null?"":addressBook.getDistrictName())
                + (addressBook.getDetail()==null?"":addressBook.getDetail())
                );//设置地址
        //保存订单数据
        this.save(order);
        //向明细表插入数据，多条数据
        orderDetailService.saveBatch(orderDetails);
        //清空购物车数据
        shoppingCartService.remove(queryWrapper);
    }
}
